package com.zxjbyte.yiyi.framework.redis.lock.executor;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * redisson 可重入锁
 * @Author zhangxingjia
 * @Date 2023/4/14 17:22
 * @Version: 1.0
 */
@Slf4j
@RequiredArgsConstructor
public class ReentrantRLockExecutor extends AbstractRLockExecutor<RLock>{

    private final RedissonClient redissonClient;

    @Override
    public RLock acquire(String lockKey, long waitTime, long leaseTime, TimeUnit unit) {
        try {
            RLock rLock = redissonClient.getLock(lockKey);
            return getLockInstance(rLock.tryLock(waitTime, leaseTime, unit), rLock);
        } catch (InterruptedException e) {
            log.error("ReentrantRLockExecutor tryLock error: ", e);
            return null;
        }
    }

    @Override
    public boolean release(String key, RLock lockInst) {
        if(lockInst.isHeldByCurrentThread()){
            try {
                return lockInst.forceUnlockAsync().get();
            } catch (InterruptedException | ExecutionException e) {
                log.error("ReentrantRLockExecutor forceUnlockAsync error", e);
                return false;
            }
        }
        return false;
    }
}
